#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import time
import selenium
from utils import Util
from config import Config
from cat_win10 import _Win10


class Category:

    def __init__(self):
        self._productId = None
        self._bDownloadUpdate = False
        self._bDownloadDrivers = False

    def get_category_id(self):
        return "win11"

    def get_category_name(self):
        return "Microsoft Windows 11"

    def get_category_cmdline_option_description(self):
        buf = ""
        buf += '--updates: download all updates.\n'
        buf += '--drivers: download all drivers.\n'
        return buf

    def set_product_and_parse_cmdline(self, productId, argv, c, dieFunc):
        self._productId = productId

        while len(argv) > c:
            if argv[c] == "--updates":
                self._bDownloadUpdate = True
                c += 1
                continue
            elif argv[c] == "--drivers":
                self._bDownloadDrivers = True
                c += 1
                continue
            else:
                break

        return c

    def get_product_id_list(self):
        # from https://www.microsoft.com/en-US/software-download/windows11
        return [
            "windows-11.x86_64.ar",                      # language: Arabic
            "windows-11.x86_64.pt-br",                   # language: Brazilian Portuguese
            "windows-11.x86_64.br",                      # language: Bulgarian
            "windows-11.x86_64.zh-cn",                   # language: Chinese Simplified
            "windows-11.x86_64.zh-tw",                   # language: Chinese Traditional
            "windows-11.x86_64.hr",                      # language: Croatian
            "windows-11.x86_64.cz",                      # language: Czech
            "windows-11.x86_64.da",                      # language: Danish
            "windows-11.x86_64.nl",                      # language: Dutch
            "windows-11.x86_64.en-us",                   # language: English
            "windows-11.x86_64.en",                      # language: English International
            "windows-11.x86_64.et",                      # language: Estonian
            "windows-11.x86_64.fi",                      # language: Finnish
            "windows-11.x86_64.fr-ca",                   # language: French Canadian
            "windows-11.x86_64.de",                      # language: German
            "windows-11.x86_64.el",                      # language: Greek
            "windows-11.x86_64.he",                      # language: Hebrew
            "windows-11.x86_64.hu",                      # language: Hungarian
            "windows-11.x86_64.it",                      # language: Italian
            "windows-11.x86_64.ja",                      # language: Japanese
            "windows-11.x86_64.ko",                      # language: Korean
            "windows-11.x86_64.lv",                      # language: Latvian
            "windows-11.x86_64.lt",                      # language: Lithuanian
            "windows-11.x86_64.nb",                      # language: Norwegian
            "windows-11.x86_64.pl",                      # language: Polish
            "windows-11.x86_64.pt-pt",                   # language: Portuguese
            "windows-11.x86_64.ro",                      # language: Romanian
            "windows-11.x86_64.ru",                      # language: Russian
            "windows-11.x86_64.sr",                      # language: Serbian Latin
            "windows-11.x86_64.sk",                      # language: Slovak
            "windows-11.x86_64.sl",                      # language: Slovenian
            "windows-11.x86_64.es",                      # language: Spanish
            "windows-11.x86_64.Spanish_(Mexico)",                                           # FIXME, "_" corresponding to " "
            "windows-11.x86_64.sv",                      # language: Swedish
            "windows-11.x86_64.th",                      # language: Thai
            "windows-11.x86_64.tr",                      # language: Turkish
            "windows-11.x86_64.uk",                      # language: Ukrainian
        ]

    def get_product_description(self, product_id):
        assert product_id in self.get_product_id_list()

        ret = ""
        edition, arch, lang = product_id.split(".")

        d = {
            "windows-11": "Microsoft Windows 11",
        }
        ret += d[edition]
        ret += ", "

        d = {
            "x86_64": "X86_64",
        }
        ret += d[arch]
        ret += ", "

        ret += _Win11.langDict[lang]

        return ret

    def download(self, cacheDir, destDir):
        localFile = _Win10.download(self._productId, cacheDir)
        finalFile = os.path.join(destDir, self._productId + ".iso")
        Util.copyFile(localFile, finalFile, os.getuid(), os.getgid())


class _Win11:

    # same as windows 10
    langDict = _Win10.langDict

    @classmethod
    def get_url_and_digest(cls, lang):
        browser = selenium.webdriver.WebKitGTK()
        browser.implicitly_wait(60)
        try:
            browser.get('https://www.microsoft.com/en-US/software-download/windows11')
            time.sleep(5)

            browser.find_element_by_id("product-edition").select_by_index(1)
            browser.find_element_by_id("submit-proudct-edition").click()
            time.sleep(5)

            browser.find_element_by_id("product-language").select_by_visible_text(cls.langDict[lang])
            browser.find_element_by_id("submit-sku").click()
            time.sleep(5)

            url = browser.find_element_by_partial_link_text('64-bit').get_attribute('href')
            digest = browser.find_element_by_xpath("//td[text='%s 64-bit']/following-sibling" % (cls.langDict[lang])).text
            return (url, digest)
        finally:
            browser.quit()

    @classmethod
    def download(cls, productId, destDir):
        downloadDir = os.path.join(Config.cacheDir, productId)
        Util.forceMkdir(downloadDir)

        edition, arch, lang = productId.split(".")
        url, digest = cls.get_url_and_digest(arch, lang)
        localFile = cls._fetchInstallIsoFileSimple(productId, url, downloadDir, fn=(productId + ".iso"), digest=digest)

        return localFile
